package cn.wgspring.wedding_helper

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import cn.wgspring.wedding_helper.model.*
import cn.wgspring.wedding_helper.settings.AppSettings
import org.jetbrains.compose.ui.tooling.preview.Preview
import kotlinx.coroutines.launch
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.zIndex
import kotlin.math.absoluteValue
import androidx.compose.animation.core.*
import androidx.compose.foundation.layout.Box
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.scale

// 定义婚礼主题颜色
object WeddingThemeColors {
    // 主题色：喜庆红色
    val PrimaryRed = Color(0xFFE53935)  // 鲜艳的红色

    // 次要主题色：浪漫粉色
    val SecondaryPink = Color(0xFFEC407A)  // 亮粉色

    // 强调色：金色
    val AccentGold = Color(0xFFFFD54F)  // 金色

    // 背景色：柔和白色
    val BackgroundWhite = Color(0xFFFFFBFA)  // 带微粉的白色

    // 辅助色：珊瑚色
    val CoralPink = Color(0xFFF48FB1)  // 珊瑚粉

    // 浅粉背景
    val LightPink = Color(0xFFFCE4EC)  // 非常浅的粉色

    // 文本颜色
    val TextDark = Color(0xFF424242)  // 深灰接近黑色
    val TextSecondary = Color(0xFF757575)  // 次要文本色
}

// 状态栏高度
val statusBarHeight = 40.dp

// 创建自定义主题
@Composable
fun WeddingTheme(content: @Composable () -> Unit) {
    val colors = lightColors(
        primary = WeddingThemeColors.PrimaryRed,
        primaryVariant = WeddingThemeColors.PrimaryRed.copy(alpha = 0.8f),
        secondary = WeddingThemeColors.SecondaryPink,
        secondaryVariant = WeddingThemeColors.CoralPink,
        background = WeddingThemeColors.BackgroundWhite,
        surface = WeddingThemeColors.BackgroundWhite,
        error = Color.Red,
        onPrimary = Color.White,
        onSecondary = Color.White,
        onBackground = WeddingThemeColors.TextDark,
        onSurface = WeddingThemeColors.TextDark,
        onError = Color.White
    )

    MaterialTheme(colors = colors, content = content)
}

// 定义导航项
data class NavItem(val title: String, val icon: ImageVector, val index: Int)

@Composable
@Preview
fun App() {
    val appSettings = remember { AppSettings.getInstance() }
    val shoppingList = remember { WeddingShoppingList() }
    val checkList = remember { WeddingCheckList() }
    val scaffoldState = rememberScaffoldState()
    val coroutineScope = rememberCoroutineScope()
    var selectedTabIndex by remember { mutableStateOf(appSettings.getSelectedTab()) }

    // 定义导航项
    val navItems = listOf(
        NavItem("备婚购物清单", Icons.Default.ShoppingCart, 0),
        NavItem("婚礼当天物品清单", Icons.Default.CheckCircle, 1)
    )

    // 保存当前选中的Tab
    LaunchedEffect(selectedTabIndex) {
        appSettings.saveSelectedTab(selectedTabIndex)
    }

    WeddingTheme {
        Box(modifier = Modifier.fillMaxSize()) {
            Scaffold(
                scaffoldState = scaffoldState,
                topBar = {
                    TopAppBar(
                        title = {
                            Text(text = navItems[selectedTabIndex].title, modifier = Modifier.padding(top = statusBarHeight))
                        },
                        navigationIcon = {
                            IconButton(onClick = {
                                coroutineScope.launch {
                                    scaffoldState.drawerState.open()
                                }
                            }, modifier = Modifier.padding(top = statusBarHeight)) {
                                Icon(imageVector = Icons.Default.Menu, contentDescription = "打开菜单")
                            }
                        },
                        elevation = 4.dp,
                        backgroundColor = MaterialTheme.colors.primary,
                        contentColor = Color.White,
                        modifier = Modifier.height(100.dp)
                    )
                },
                drawerContent = {
                    DrawerHeader()
                    Spacer(modifier = Modifier.height(16.dp))
                    navItems.forEach { navItem ->
                        DrawerItem(item = navItem, selected = selectedTabIndex == navItem.index, onItemClick = {
                            selectedTabIndex = navItem.index
                            coroutineScope.launch {
                                scaffoldState.drawerState.close()
                            }
                        })
                    }
                },
            ) {
                // 内容区域
                Box(modifier = Modifier.fillMaxSize()) {
                    when (selectedTabIndex) {
                        0 -> ShoppingListScreen(shoppingList)
                        1 -> CheckListScreen(checkList)
                    }
                }
            }
        }
    }
}

@Composable
fun DrawerHeader() {
    Box(
        modifier = Modifier.fillMaxWidth().background(color = WeddingThemeColors.LightPink).padding(vertical = 16.dp),
        contentAlignment = Alignment.Center
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
            Spacer(modifier = Modifier.height(statusBarHeight))
            Icon(
                imageVector = Icons.Default.Favorite,
                contentDescription = null,
                modifier = Modifier.size(80.dp),
                tint = MaterialTheme.colors.primary
            )
            Spacer(modifier = Modifier.height(16.dp))
            Text(
                text = "轻松备婚",
                fontSize = 22.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colors.primary
            )
        }
    }
    Divider()
}

@Composable
fun DrawerItem(item: NavItem, selected: Boolean, onItemClick: () -> Unit) {
    val backgroundColor = if (selected) {
        WeddingThemeColors.LightPink
    } else {
        Color.Transparent
    }

    val contentColor = if (selected) {
        MaterialTheme.colors.primary
    } else {
        MaterialTheme.colors.onSurface
    }

    Surface(modifier = Modifier.fillMaxWidth(), color = backgroundColor) {
        Row(
            modifier = Modifier.fillMaxWidth().padding(16.dp).clickable(onClick = onItemClick),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(imageVector = item.icon, contentDescription = null, tint = contentColor)
            Spacer(modifier = Modifier.width(32.dp))
            Text(text = item.title, color = contentColor, style = MaterialTheme.typography.body1)
        }
    }
}

@Composable
fun ShoppingListScreen(shoppingList: WeddingShoppingList) {
    val appSettings = remember { AppSettings.getInstance() }
    var showAddDialog by remember { mutableStateOf(false) }
    var showAddTimePhaseDialog by remember { mutableStateOf(false) }
    var isFabExpanded by remember { mutableStateOf(false) }

    // 动画相关
    val transition = updateTransition(isFabExpanded, label = "FAB展开动画")

    // 添加时间阶段按钮的位移和缩放动画
    val timePhaseOffset by transition.animateDp(
        transitionSpec = { tween(durationMillis = 200) }, label = "时间阶段按钮位移"
    ) { expanded -> if (expanded) 68.dp else 0.dp }

    val timePhaseScale by transition.animateFloat(
        transitionSpec = { tween(durationMillis = 200) }, label = "时间阶段按钮缩放"
    ) { expanded -> if (expanded) 1f else 0f }

    // 添加物品按钮的位移和缩放动画
    val itemOffset by transition.animateDp(
        transitionSpec = { tween(durationMillis = 200) }, label = "物品按钮位移"
    ) { expanded -> if (expanded) 128.dp else 0.dp }

    val itemScale by transition.animateFloat(
        transitionSpec = { tween(durationMillis = 200) }, label = "物品按钮缩放"
    ) { expanded -> if (expanded) 1f else 0f }

    Box(modifier = Modifier.fillMaxSize()) {
        LazyColumn(modifier = Modifier.fillMaxSize().padding(bottom = 16.dp, start = 16.dp, end = 16.dp)) {
            // 按时间段展示购物清单
            val itemsByTimePhase = shoppingList.getItemsByTimePhase()
            itemsByTimePhase.forEach { (timePhase, items) ->
                item {
                    Spacer(modifier = Modifier.height(16.dp))
                    TimePhaseSection(
                        timePhase = timePhase,
                        items = items,
                        shoppingList = shoppingList,
                        initialExpanded = appSettings.getTimePhaseExpandedState(timePhase),
                        onExpandedChange = { expanded ->
                            appSettings.saveTimePhaseExpandedState(timePhase, expanded)
                        })
                }
            }
            item {
                Spacer(modifier = Modifier.height(56.dp))
            }
        }


        // 可展开的悬浮按钮组
        Box(modifier = Modifier.align(Alignment.BottomEnd).padding(32.dp)) {
            // 背景遮罩，只在展开时可点击
            if (isFabExpanded) {
                Box(modifier = Modifier.fillMaxSize().background(Color.Transparent).clickable { isFabExpanded = false })
            }

            // 添加时间阶段按钮（使用动画值）
            FloatingActionButton(
                content = {
                    Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.align(Alignment.CenterStart).padding(horizontal = 8.dp)) {
                        Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.padding(horizontal = 8.dp))
                        Text("添加时间阶段")
                    }
                },
                onClick = {
                    showAddTimePhaseDialog = true
                    isFabExpanded = false
                },
                backgroundColor = WeddingThemeColors.PrimaryRed,
                contentColor = Color.White,
                modifier = Modifier.align(Alignment.BottomEnd)
                    .padding(bottom = timePhaseOffset)
                    .width(160.dp)
                    .height(46.dp)
                    .scale(timePhaseScale)
                    .alpha(timePhaseScale)
            )

            // 添加物品按钮（使用动画值）
            FloatingActionButton(
                content = {
                    Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.align(Alignment.CenterStart).padding(horizontal = 8.dp)) {
                        Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.padding(horizontal = 8.dp))
                        Text("添加物品")
                    }
                },
                onClick = {
                    showAddDialog = true
                    isFabExpanded = false
                },
                backgroundColor = WeddingThemeColors.PrimaryRed,
                contentColor = Color.White,
                modifier = Modifier.align(Alignment.BottomEnd)
                    .padding(bottom = itemOffset)
                    .width(160.dp)
                    .height(46.dp)
                    .scale(itemScale)
                    .alpha(itemScale)
            )

            // 主悬浮按钮
            FloatingActionButton(
                onClick = { isFabExpanded = !isFabExpanded },
                backgroundColor = WeddingThemeColors.PrimaryRed,
                contentColor = Color.White,
                modifier = Modifier.align(Alignment.BottomEnd)
            ) {
                // 旋转动画
                val rotation by transition.animateFloat(
                    transitionSpec = { tween(durationMillis = 200) }, label = "旋转动画"
                ) { expanded -> if (expanded) 45f else 0f }

                Icon(
                    imageVector = Icons.Default.Add,
                    contentDescription = if (isFabExpanded) "关闭菜单" else "打开添加菜单",
                    modifier = Modifier.rotate(rotation)
                )
            }
        }

        // 添加物品对话框
        if (showAddDialog) {
            AddShoppingItemDialog(shoppingList = shoppingList, onDismiss = { showAddDialog = false })
        }

        // 添加时间阶段对话框
        if (showAddTimePhaseDialog) {
            AddTimePhaseDialog(shoppingList = shoppingList, onDismiss = { showAddTimePhaseDialog = false })
        }
    }
}

@Composable
fun CheckListScreen(checkList: WeddingCheckList) {
    val appSettings = remember { AppSettings.getInstance() }
    var showAddDialog by remember { mutableStateOf(false) }
    var showAddUserGroupDialog by remember { mutableStateOf(false) }
    var isFabExpanded by remember { mutableStateOf(false) }

    // 动画相关
    val transition = updateTransition(isFabExpanded, label = "FAB展开动画")

    // 添加使用方按钮的位移和缩放动画
    val userGroupOffset by transition.animateDp(
        transitionSpec = { tween(durationMillis = 200) }, label = "使用方按钮位移"
    ) { expanded -> if (expanded) 68.dp else 0.dp }

    val userGroupScale by transition.animateFloat(
        transitionSpec = { tween(durationMillis = 200) }, label = "使用方按钮缩放"
    ) { expanded -> if (expanded) 1f else 0f }

    // 添加物品按钮的位移和缩放动画
    val itemOffset by transition.animateDp(
        transitionSpec = { tween(durationMillis = 200) }, label = "物品按钮位移"
    ) { expanded -> if (expanded) 128.dp else 0.dp }

    val itemScale by transition.animateFloat(
        transitionSpec = { tween(durationMillis = 200) }, label = "物品按钮缩放"
    ) { expanded -> if (expanded) 1f else 0f }

    Box(modifier = Modifier.fillMaxSize()) {
        LazyColumn(modifier = Modifier.fillMaxSize().padding(bottom = 16.dp, start = 16.dp, end = 16.dp)) {
            // 按使用方分组展示检查清单
            val itemsByUserGroup = checkList.getItemsByUserGroup()
            itemsByUserGroup.forEach { (userGroup, items) ->
                item {
                    Spacer(modifier = Modifier.height(16.dp))
                    UserGroupSection(
                        userGroup = userGroup,
                        items = items,
                        checkList = checkList,
                        initialExpanded = appSettings.getUserGroupExpandedState(userGroup),
                        onExpandedChange = { expanded ->
                            appSettings.saveUserGroupExpandedState(userGroup, expanded)
                        })
                }
            }
            item {
                Spacer(modifier = Modifier.height(56.dp))
            }
        }

        // 可展开的悬浮按钮组
        Box(modifier = Modifier.align(Alignment.BottomEnd).padding(32.dp)) {
            // 背景遮罩，只在展开时可点击
            if (isFabExpanded) {
                Box(modifier = Modifier.fillMaxSize().background(Color.Transparent).clickable { isFabExpanded = false })
            }

            // 添加使用方按钮（使用动画值）
            FloatingActionButton(
                content = {
                    Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.align(Alignment.CenterStart).padding(horizontal = 8.dp)) {
                        Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.padding(horizontal = 8.dp))
                        Text("添加使用方")
                    }
                },
                onClick = {
                    showAddUserGroupDialog = true
                    isFabExpanded = false
                },
                backgroundColor = WeddingThemeColors.PrimaryRed,
                contentColor = Color.White,
                modifier = Modifier.align(Alignment.BottomEnd).padding(bottom = userGroupOffset).scale(userGroupScale)
                    .width(160.dp)
                    .height(46.dp)
                    .alpha(userGroupScale)
            )


            // 添加物品按钮（使用动画值）
            FloatingActionButton(
                content = {
                    Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.align(Alignment.CenterStart).padding(horizontal = 8.dp)) {
                        Icon(Icons.Default.Add, contentDescription = null, modifier = Modifier.padding(horizontal = 8.dp))
                        Text("添加物品")
                    }
                },
                onClick = {
                    showAddDialog = true
                    isFabExpanded = false
                },
                backgroundColor = WeddingThemeColors.PrimaryRed,
                contentColor = Color.White,
                modifier = Modifier.align(Alignment.BottomEnd).padding(bottom = itemOffset).scale(itemScale)
                    .width(160.dp)
                    .height(46.dp)
                    .alpha(itemScale)
            )

            // 主悬浮按钮
            FloatingActionButton(
                onClick = { isFabExpanded = !isFabExpanded },
                backgroundColor = WeddingThemeColors.PrimaryRed,
                contentColor = Color.White,
                modifier = Modifier.align(Alignment.BottomEnd)
            ) {
                // 旋转动画
                val rotation by transition.animateFloat(
                    transitionSpec = { tween(durationMillis = 200) }, label = "旋转动画"
                ) { expanded -> if (expanded) 45f else 0f }

                Icon(
                    imageVector = Icons.Default.Add,
                    contentDescription = if (isFabExpanded) "关闭菜单" else "打开添加菜单",
                    modifier = Modifier.rotate(rotation)
                )
            }
        }

        // 添加物品对话框
        if (showAddDialog) {
            AddCheckListItemDialog(checkList = checkList, onDismiss = { showAddDialog = false })
        }

        // 添加使用方对话框
        if (showAddUserGroupDialog) {
            AddUserGroupDialog(checkList = checkList, onDismiss = { showAddUserGroupDialog = false })
        }
    }
}

@Composable
fun UserGroupSection(
    userGroup: String,
    items: List<CheckListItem>,
    checkList: WeddingCheckList,
    initialExpanded: Boolean = true,
    onExpandedChange: (Boolean) -> Unit = {}
) {
    var expanded by remember { mutableStateOf(initialExpanded) }

    // 检查是否所有物品都已确认
    val allConfirmed = items.isNotEmpty() && items.all { it.isConfirmed }

    Card(
        modifier = Modifier.fillMaxWidth(), elevation = 4.dp, border = BorderStroke(
            1.dp, if (allConfirmed) WeddingThemeColors.AccentGold else MaterialTheme.colors.primary.copy(alpha = 0.5f)
        ), shape = RoundedCornerShape(12.dp), backgroundColor = MaterialTheme.colors.surface
    ) {
        Column(modifier = Modifier.padding(8.dp)) {
            // 使用方标题栏
            Row(
                modifier = Modifier.fillMaxWidth().background(
                    if (allConfirmed) WeddingThemeColors.AccentGold.copy(alpha = 0.25f)
                    else WeddingThemeColors.LightPink, RoundedCornerShape(8.dp)
                ).padding(8.dp).clickable(true, onClick = {
                    expanded = !expanded
                    onExpandedChange(expanded)
                }), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        text = userGroup,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colors.primary
                    )

                    // 显示完成状态
                    if (allConfirmed) {
                        Spacer(modifier = Modifier.width(8.dp))
                        Card(
                            backgroundColor = WeddingThemeColors.AccentGold,
                            shape = RoundedCornerShape(16.dp),
                            elevation = 0.dp
                        ) {
                            Row(
                                modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    imageVector = Icons.Default.CheckCircle,
                                    contentDescription = null,
                                    modifier = Modifier.size(16.dp),
                                    tint = Color.White
                                )
                                Spacer(modifier = Modifier.width(4.dp))
                                Text(
                                    text = "已完成", fontSize = 12.sp, color = Color.White, fontWeight = FontWeight.Bold
                                )
                            }
                        }
                    }
                }

                Icon(
                    imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                    contentDescription = if (expanded) "收起" else "展开",
                    tint = MaterialTheme.colors.primary
                )

            }

            // 展开时显示物品列表
            if (expanded) {
                Spacer(modifier = Modifier.height(8.dp))

                // 显示物品列表
                items.forEach { item ->
                    CheckListItemRow(item, checkList)
                }
            }
        }
    }
}

@Composable
fun CheckListItemRow(item: CheckListItem, checkList: WeddingCheckList) {
    val appSettings = remember { AppSettings.getInstance() }
    var isEditing by remember { mutableStateOf(false) }
    var offsetX by remember { mutableStateOf(0f) }
    val buttonWidth = 60.dp

    Box(modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min).padding(vertical = 4.dp, horizontal = 0.dp)) {
        // 删除和编辑按钮区域 - 固定在右侧
        Row(
            modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight().zIndex(0f),
            horizontalArrangement = Arrangement.End
        ) {
            // 编辑按钮 - 左侧按钮
            Box(
                modifier = Modifier.fillMaxHeight().width(buttonWidth + 16.dp)      // 增加16dp的宽度以适应圆角
                    .background(Color(0xFF2196F3)).clickable {
                        isEditing = true
                        offsetX = 0f
                    }, contentAlignment = Alignment.Center
            ) {
                Icon(imageVector = Icons.Default.Edit, contentDescription = "编辑", tint = Color.White)
            }

            // 删除按钮 - 右侧按钮，添加圆角
            Box(
                modifier = Modifier.fillMaxHeight().width(buttonWidth)
                    .clip(shape = RoundedCornerShape(0.dp, 8.dp, 8.dp, 0.dp)).background(Color(0xFFF44336)).clickable {
                        // 删除物品，并持久化删除状态
                        checkList.removeItem(item)
                        offsetX = 0f
                    }, contentAlignment = Alignment.Center
            ) {
                Icon(imageVector = Icons.Default.Delete, contentDescription = "删除", tint = Color.White)
            }
        }

        // 主要内容
        Card(modifier = Modifier.fillMaxWidth().offset(x = offsetX.dp).zIndex(1f).pointerInput(Unit) {
            detectHorizontalDragGestures(onDragEnd = {
                if (offsetX.absoluteValue < 40) {
                    // 如果拖动距离小，则回弹
                    offsetX = 0f
                } else {
                    // 否则，停在按钮宽度的位置
                    offsetX = -(buttonWidth.value * 2)
                }
            }, onDragCancel = {
                offsetX = 0f
            }, onHorizontalDrag = { _, dragAmount ->
                val newOffset = offsetX + dragAmount
                offsetX = when {
                    newOffset > 0 -> 0f  // 不允许向右拖过头
                    newOffset < -(buttonWidth.value * 2) -> -(buttonWidth.value * 2)  // 限制最大拖动距离为两个按钮的宽度
                    else -> newOffset
                }
            })
        }, elevation = 1.dp, shape = RoundedCornerShape(8.dp)) {
            Row(
                modifier = Modifier.fillMaxWidth()
                    .padding(vertical = 8.dp, horizontal = 8.dp)
                    .background(MaterialTheme.colors.surface)
                    .clickable(true, onClick = {
                        checkList.toggleItemConfirmation(item)
                    }),
            ) {
                // 勾选框
                Checkbox(checked = item.isConfirmed, onCheckedChange = {
                    checkList.toggleItemConfirmation(item)
                }, colors = CheckboxDefaults.colors(checkedColor = MaterialTheme.colors.primary))

                // 物品信息
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = item.name,
                        fontWeight = FontWeight.Medium,
                        color = if (item.isConfirmed) Color.Gray else Color.Black,
                        overflow = TextOverflow.Ellipsis,
                        maxLines = 1,
                        modifier = Modifier.padding(top = 12.dp)
                    )

                    if (item.purpose.isNotEmpty()) {
                        Text(
                            text = "用途: ${item.purpose}",
                            fontSize = 12.sp,
                            color = Color.Gray,
                            modifier = Modifier.padding(top = 4.dp),
                            overflow = TextOverflow.Ellipsis,
                            maxLines = 1
                        )
                    }

                    if (item.location.isNotEmpty()) {
                        Text(
                            text = "地点: ${item.location}",
                            fontSize = 12.sp,
                            color = Color.Gray,
                            modifier = Modifier.padding(top = 2.dp),
                            overflow = TextOverflow.Ellipsis,
                            maxLines = 1
                        )
                    }
                }
            }
        }

        // 编辑对话框
        if (isEditing) {
            EditCheckListItemDialog(
                item = item,
                onDismiss = { isEditing = false },
                onConfirm = { editedName, editedPurpose, editedLocation ->
                    // 更新物品信息，并持久化编辑状态
                    checkList.updateItem(item, editedName, editedPurpose, editedLocation)
                    isEditing = false
                })
        }
    }
}

@Composable
fun TimePhaseSection(
    timePhase: String,
    items: List<ShoppingItem>,
    shoppingList: WeddingShoppingList,
    initialExpanded: Boolean = true,
    onExpandedChange: (Boolean) -> Unit = {}
) {
    var expanded by remember { mutableStateOf(initialExpanded) }
    val itemsByCategory = shoppingList.getItemsByCategoryInTimePhase(timePhase, items)

    // 检查是否所有物品都已购买
    val allPurchased = items.isNotEmpty() && items.all { it.isPurchased }

    Card(
        modifier = Modifier.fillMaxWidth(), elevation = 4.dp, border = BorderStroke(
            1.dp, if (allPurchased) WeddingThemeColors.AccentGold else MaterialTheme.colors.primary.copy(alpha = 0.5f)
        ), shape = RoundedCornerShape(12.dp), backgroundColor = MaterialTheme.colors.surface
    ) {
        Column(modifier = Modifier.padding(8.dp)) {
            // 时间段标题栏
            Row(
                modifier = Modifier.fillMaxWidth().background(
                    if (allPurchased) WeddingThemeColors.AccentGold.copy(alpha = 0.25f) else WeddingThemeColors.LightPink,
                    RoundedCornerShape(8.dp)
                ).padding(8.dp).clickable(true, onClick = {
                    expanded = !expanded
                    onExpandedChange(expanded)
                }),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        text = timePhase,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colors.primary
                    )

                    // 显示完成状态
                    if (allPurchased) {
                        Spacer(modifier = Modifier.width(8.dp))
                        Card(
                            backgroundColor = WeddingThemeColors.AccentGold,
                            shape = RoundedCornerShape(16.dp),
                            elevation = 0.dp
                        ) {
                            Row(
                                modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    imageVector = Icons.Default.CheckCircle,
                                    contentDescription = null,
                                    modifier = Modifier.size(16.dp),
                                    tint = Color.White
                                )
                                Spacer(modifier = Modifier.width(4.dp))
                                Text(
                                    text = "已完成", fontSize = 12.sp, color = Color.White, fontWeight = FontWeight.Bold
                                )
                            }
                        }
                    }
                }
                Icon(
                    imageVector = if (expanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                    contentDescription = if (expanded) "收起" else "展开",
                    tint = MaterialTheme.colors.primary
                )
            }

            // 展开时显示物品列表
            if (expanded) {
                Spacer(modifier = Modifier.height(8.dp))

                // 按类别分组显示物品
                itemsByCategory.forEach { (category, categoryItems) ->
                    CategorySection(category, categoryItems, shoppingList)
                    Spacer(modifier = Modifier.height(8.dp))
                }
            }
        }
    }
}

@Composable
fun CategorySection(category: String, items: List<ShoppingItem>, shoppingList: WeddingShoppingList) {
    Column(modifier = Modifier.fillMaxWidth()) {
        // 类别标题
        Text(
            text = category,
            fontSize = 16.sp,
            fontWeight = FontWeight.SemiBold,
            modifier = Modifier.background(WeddingThemeColors.LightPink.copy(alpha = 0.3f), RoundedCornerShape(4.dp))
                .padding(vertical = 4.dp, horizontal = 8.dp),
            color = MaterialTheme.colors.secondary
        )

        // 物品列表
        items.forEach { item ->
            ShoppingItemRow(item, shoppingList)
        }
    }
}

@Composable
fun ShoppingItemRow(item: ShoppingItem, shoppingList: WeddingShoppingList) {
    val appSettings = remember { AppSettings.getInstance() }
    var isEditing by remember { mutableStateOf(false) }
    var offsetX by remember { mutableStateOf(0f) }
    val buttonWidth = 60.dp

    Box(modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min).padding(vertical = 4.dp, horizontal = 0.dp)) {
        // 删除和编辑按钮区域 - 固定在右侧
        Row(
            modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight().zIndex(0f),
            horizontalArrangement = Arrangement.End
        ) {
            // 编辑按钮 - 左侧按钮
            Box(
                modifier = Modifier.fillMaxHeight().width(buttonWidth + 16.dp)      // 增加16dp的宽度以适应圆角
                    .background(Color(0xFF2196F3)).clickable {
                        isEditing = true
                        offsetX = 0f
                    }, contentAlignment = Alignment.Center
            ) {
                Icon(imageVector = Icons.Default.Edit, contentDescription = "编辑", tint = Color.White)
            }

            // 删除按钮 - 右侧按钮，添加圆角
            Box(
                modifier = Modifier.fillMaxHeight().width(buttonWidth)
                    .clip(shape = RoundedCornerShape(0.dp, 8.dp, 8.dp, 0.dp)).background(Color(0xFFF44336)).clickable {
                        // 删除物品，并持久化删除状态
                        shoppingList.removeItem(item)
                        offsetX = 0f
                    }, contentAlignment = Alignment.Center
            ) {
                Icon(imageVector = Icons.Default.Delete, contentDescription = "删除", tint = Color.White)
            }
        }

        // 主要内容
        Card(modifier = Modifier.fillMaxWidth().offset(x = offsetX.dp).zIndex(1f).pointerInput(Unit) {
            detectHorizontalDragGestures(onDragEnd = {
                if (offsetX.absoluteValue < 40) {
                    // 如果拖动距离小，则回弹
                    offsetX = 0f
                } else {
                    // 否则，停在按钮宽度的位置
                    offsetX = -(buttonWidth.value * 2)
                }
            }, onDragCancel = {
                offsetX = 0f
            }, onHorizontalDrag = { _, dragAmount ->
                val newOffset = offsetX + dragAmount
                offsetX = when {
                    newOffset > 0 -> 0f  // 不允许向右拖过头
                    newOffset < -(buttonWidth.value * 2) -> -(buttonWidth.value * 2)  // 限制最大拖动距离为两个按钮的宽度
                    else -> newOffset
                }
            })
        }, elevation = 1.dp, shape = RoundedCornerShape(8.dp)) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 4.dp, horizontal = 8.dp)
                    .background(MaterialTheme.colors.surface)
                    .clickable(true, onClick = {
                        shoppingList.toggleItemPurchased(item)
                    }),
            ) {
                // 勾选框
                Checkbox(checked = item.isPurchased, onCheckedChange = {
                    shoppingList.toggleItemPurchased(item)
                }, colors = CheckboxDefaults.colors(checkedColor = MaterialTheme.colors.primary))

                // 物品信息
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = item.name,
                        fontWeight = FontWeight.Medium,
                        color = if (item.isPurchased) Color.Gray else Color.Black,
                        overflow = TextOverflow.Ellipsis,
                        maxLines = 1,
                        modifier = Modifier.padding(top = 12.dp)
                    )
                    Row {
                        Text(
                            text = "数量: ${item.quantity}",
                            fontSize = 12.sp,
                            color = Color.Gray,
                            modifier = Modifier.padding(end = 8.dp),
                            overflow = TextOverflow.Ellipsis,
                            maxLines = 1
                        )
                        if (item.note.isNotEmpty()) {
                            Text(
                                text = "备注: ${item.note}",
                                fontSize = 12.sp,
                                color = Color.Gray,
                                overflow = TextOverflow.Ellipsis,
                                maxLines = 1
                            )
                        }
                    }
                }
            }
        }

        // 编辑对话框
        if (isEditing) {
            EditShoppingItemDialog(
                item = item,
                onDismiss = { isEditing = false },
                onConfirm = { editedName, editedCategory, editedQuantity, editedNote ->
                    // 更新物品信息，并持久化编辑状态
                    shoppingList.updateItem(item, editedName, editedCategory, editedQuantity, editedNote)
                    isEditing = false
                })
        }
    }
}

@Composable
fun EditCheckListItemDialog(
    item: CheckListItem, onDismiss: () -> Unit, onConfirm: (name: String, purpose: String, location: String) -> Unit
) {
    var name by remember { mutableStateOf(item.name) }
    var purpose by remember { mutableStateOf(item.purpose) }
    var location by remember { mutableStateOf(item.location) }

    AlertDialog(onDismissRequest = onDismiss, title = {
        Text("编辑物品", color = MaterialTheme.colors.primary, fontWeight = FontWeight.Bold)
    }, text = {
        Column(modifier = Modifier.padding(top = 8.dp)) {
            Text("物品名称", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = name,
                onValueChange = { name = it },
                label = { Text("物品名称") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(8.dp))

            Text("用途", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = purpose,
                onValueChange = { purpose = it },
                label = { Text("用途") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(8.dp))

            Text("地点", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = location,
                onValueChange = { location = it },
                label = { Text("地点") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )
        }
    }, confirmButton = {
        Button(
            onClick = {
                onConfirm(name, purpose, location)
            }, colors = ButtonDefaults.buttonColors(
                backgroundColor = MaterialTheme.colors.primary, contentColor = Color.White
            )
        ) {
            Text("确定")
        }
    }, dismissButton = {
        TextButton(
            onClick = onDismiss, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colors.primary)
        ) {
            Text("取消")
        }
    }, backgroundColor = WeddingThemeColors.BackgroundWhite, shape = RoundedCornerShape(16.dp))
}

@Composable
fun EditShoppingItemDialog(
    item: ShoppingItem,
    onDismiss: () -> Unit,
    onConfirm: (name: String, category: String, quantity: String, note: String) -> Unit
) {
    var name by remember { mutableStateOf(item.name) }
    var category by remember { mutableStateOf(item.category) }
    var quantity by remember { mutableStateOf(item.quantity) }
    var note by remember { mutableStateOf(item.note) }

    AlertDialog(onDismissRequest = onDismiss, title = {
        Text("编辑物品", color = MaterialTheme.colors.primary, fontWeight = FontWeight.Bold)
    }, text = {
        Column(modifier = Modifier.padding(top = 8.dp)) {
            Text("物品名称", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = name,
                onValueChange = { name = it },
                label = { Text("物品名称") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(8.dp))

            Text("物品类别", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = category,
                onValueChange = { category = it },
                label = { Text("物品类别") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(8.dp))

            Text("数量", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = quantity,
                onValueChange = { quantity = it },
                label = { Text("数量") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(8.dp))

            Text("备注", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = note,
                onValueChange = { note = it },
                label = { Text("备注") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )
        }
    }, confirmButton = {
        Button(
            onClick = {
                onConfirm(name, category, quantity, note)
            }, colors = ButtonDefaults.buttonColors(
                backgroundColor = MaterialTheme.colors.primary, contentColor = Color.White
            )
        ) {
            Text("确定")
        }
    }, dismissButton = {
        TextButton(
            onClick = onDismiss, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colors.primary)
        ) {
            Text("取消")
        }
    }, backgroundColor = WeddingThemeColors.BackgroundWhite, shape = RoundedCornerShape(16.dp))
}

@Composable
fun AddShoppingItemDialog(shoppingList: WeddingShoppingList, onDismiss: () -> Unit) {
    var name by remember { mutableStateOf("") }
    var category by remember { mutableStateOf("") }
    var timePhase by remember { mutableStateOf("") }
    var quantity by remember { mutableStateOf("") }
    var note by remember { mutableStateOf("") }

    // 获取现有的时间阶段列表
    val timePhases = shoppingList.getItemsByTimePhase().keys.toList()
    // 如果有现有时间阶段，默认选中第一个
    if (timePhase.isEmpty() && timePhases.isNotEmpty()) {
        timePhase = timePhases[0]
    }

    // 获取选中时间阶段下的类别列表
    val categories = shoppingList.getItemsByTimePhase()[timePhase]?.map { it.category }?.distinct() ?: listOf()

    AlertDialog(onDismissRequest = onDismiss, title = {
        Text("添加物品", color = MaterialTheme.colors.primary, fontWeight = FontWeight.Bold)
    }, text = {
        Column(modifier = Modifier.padding(top = 8.dp)) {
            // 时间阶段下拉选择
            Text("时间阶段", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            DropdownMenu(
                expanded = false, // 这里设为false，我们将自己管理下拉菜单的显示
                onDismissRequest = { }, modifier = Modifier.fillMaxWidth()
            ) {}

            var expandedTimePhase by remember { mutableStateOf(false) }
            OutlinedTextField(
                value = timePhase,
                onValueChange = { },
                label = { Text("选择时间阶段") },
                readOnly = true,
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                trailingIcon = {
                    IconButton(onClick = { expandedTimePhase = !expandedTimePhase }) {
                        Icon(
                            if (expandedTimePhase) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown,
                            "切换时间阶段下拉菜单",
                            tint = MaterialTheme.colors.primary
                        )
                    }
                },
                modifier = Modifier.fillMaxWidth().clickable { expandedTimePhase = true })
            DropdownMenu(
                expanded = expandedTimePhase,
                onDismissRequest = { expandedTimePhase = false },
                modifier = Modifier.fillMaxWidth()
            ) {
                timePhases.forEach { phase ->
                    DropdownMenuItem(onClick = {
                        timePhase = phase
                        expandedTimePhase = false
                    }) {
                        Text(phase)
                    }
                }
            }

            Spacer(modifier = Modifier.height(8.dp))

            // 类别选择或输入
            Text("类别", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            var expandedCategory by remember { mutableStateOf(false) }
            OutlinedTextField(
                value = category,
                onValueChange = { category = it },
                label = { Text("输入或选择类别") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                trailingIcon = {
                    if (categories.isNotEmpty()) {
                        IconButton(onClick = { expandedCategory = !expandedCategory }) {
                            Icon(
                                if (expandedCategory) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown,
                                "切换类别下拉菜单",
                                tint = MaterialTheme.colors.primary
                            )
                        }
                    }
                },
                modifier = Modifier.fillMaxWidth()
            )
            if (categories.isNotEmpty()) {
                DropdownMenu(
                    expanded = expandedCategory,
                    onDismissRequest = { expandedCategory = false },
                    modifier = Modifier.fillMaxWidth()
                ) {
                    categories.forEach { cat ->
                        DropdownMenuItem(onClick = {
                            category = cat
                            expandedCategory = false
                        }) {
                            Text(cat)
                        }
                    }
                }
            }

            Spacer(modifier = Modifier.height(8.dp))

            // 物品名称
            Text("物品名称", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = name,
                onValueChange = { name = it },
                label = { Text("物品名称") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(8.dp))

            // 数量
            Text("数量", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = quantity,
                onValueChange = { quantity = it },
                label = { Text("数量") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(8.dp))

            // 备注
            Text("备注", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = note,
                onValueChange = { note = it },
                label = { Text("备注") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )
        }
    }, confirmButton = {
        Button(
            onClick = {
                if (name.isNotBlank() && timePhase.isNotBlank()) {
                    // 创建新物品并添加到列表
                    val newItem = ShoppingItem(
                        id = -1, // ID将由存储管理器分配
                        name = name,
                        category = if (category.isBlank()) "未分类" else category,
                        timePhase = timePhase,
                        quantity = quantity,
                        note = note,
                        purchased = false
                    )
                    shoppingList.addItem(newItem)
                    onDismiss()
                }
            }, enabled = name.isNotBlank() && timePhase.isNotBlank(), colors = ButtonDefaults.buttonColors(
                backgroundColor = MaterialTheme.colors.primary, contentColor = Color.White
            )
        ) {
            Text("添加")
        }
    }, dismissButton = {
        TextButton(
            onClick = onDismiss, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colors.primary)
        ) {
            Text("取消")
        }
    }, backgroundColor = WeddingThemeColors.BackgroundWhite, shape = RoundedCornerShape(16.dp))
}

@Composable
fun AddTimePhaseDialog(shoppingList: WeddingShoppingList, onDismiss: () -> Unit) {
    var timePhase by remember { mutableStateOf("") }

    AlertDialog(onDismissRequest = onDismiss, title = {
        Text("添加时间阶段", color = MaterialTheme.colors.primary, fontWeight = FontWeight.Bold)
    }, text = {
        Column(modifier = Modifier.padding(top = 8.dp)) {
            Text("时间阶段名称", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = timePhase,
                onValueChange = { timePhase = it },
                label = { Text("时间阶段名称") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )
        }
    }, confirmButton = {
        Button(
            onClick = {
                if (timePhase.isNotBlank()) {
                    // 添加新的时间阶段
                    val dummyItem = ShoppingItem(
                        id = -1, name = "占位物品", // 创建一个占位物品，确保时间阶段被添加
                        category = "未分类", timePhase = timePhase, quantity = "", note = "", purchased = false
                    )
                    shoppingList.addItem(dummyItem)
                    shoppingList.removeItem(dummyItem) // 立即删除占位物品
                    onDismiss()
                }
            }, enabled = timePhase.isNotBlank(), colors = ButtonDefaults.buttonColors(
                backgroundColor = MaterialTheme.colors.primary, contentColor = Color.White
            )
        ) {
            Text("添加")
        }
    }, dismissButton = {
        TextButton(
            onClick = onDismiss, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colors.primary)
        ) {
            Text("取消")
        }
    }, backgroundColor = WeddingThemeColors.BackgroundWhite, shape = RoundedCornerShape(16.dp))
}

@Composable
fun AddCheckListItemDialog(checkList: WeddingCheckList, onDismiss: () -> Unit) {
    var name by remember { mutableStateOf("") }
    var userGroup by remember { mutableStateOf("") }
    var purpose by remember { mutableStateOf("") }
    var location by remember { mutableStateOf("") }

    // 获取现有的使用方列表
    val userGroups = checkList.getItemsByUserGroup().keys.toList()
    // 如果有现有使用方，默认选中第一个
    if (userGroup.isEmpty() && userGroups.isNotEmpty()) {
        userGroup = userGroups[0]
    }

    AlertDialog(onDismissRequest = onDismiss, title = {
        Text("添加物品", color = MaterialTheme.colors.primary, fontWeight = FontWeight.Bold)
    }, text = {
        Column(modifier = Modifier.padding(top = 8.dp)) {
            // 使用方下拉选择
            Text("使用方", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            var expandedUserGroup by remember { mutableStateOf(false) }
            OutlinedTextField(
                value = userGroup,
                onValueChange = { },
                label = { Text("选择使用方") },
                readOnly = true,
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                trailingIcon = {
                    IconButton(onClick = { expandedUserGroup = !expandedUserGroup }) {
                        Icon(
                            if (expandedUserGroup) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown,
                            "切换使用方下拉菜单",
                            tint = MaterialTheme.colors.primary
                        )
                    }
                },
                modifier = Modifier.fillMaxWidth().clickable { expandedUserGroup = true })
            DropdownMenu(
                expanded = expandedUserGroup,
                onDismissRequest = { expandedUserGroup = false },
                modifier = Modifier.fillMaxWidth()
            ) {
                userGroups.forEach { group ->
                    DropdownMenuItem(onClick = {
                        userGroup = group
                        expandedUserGroup = false
                    }) {
                        Text(group)
                    }
                }
            }

            Spacer(modifier = Modifier.height(8.dp))

            // 物品名称
            Text("物品名称", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = name,
                onValueChange = { name = it },
                label = { Text("物品名称") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(8.dp))

            // 用途
            Text("用途", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = purpose,
                onValueChange = { purpose = it },
                label = { Text("用途") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )

            Spacer(modifier = Modifier.height(8.dp))

            // 地点
            Text("地点", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = location,
                onValueChange = { location = it },
                label = { Text("地点") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )
        }
    }, confirmButton = {
        Button(
            onClick = {
                if (name.isNotBlank() && userGroup.isNotBlank()) {
                    // 创建新物品并添加到列表
                    val newItem = CheckListItem(
                        id = -1, // ID将由存储管理器分配
                        name = name,
                        userGroup = userGroup,
                        purpose = purpose,
                        location = location,
                        confirmed = false,
                        userDefined = true,
                        isDeleted = false
                    )
                    checkList.addItem(newItem)
                    onDismiss()
                }
            }, enabled = name.isNotBlank() && userGroup.isNotBlank(), colors = ButtonDefaults.buttonColors(
                backgroundColor = MaterialTheme.colors.primary, contentColor = Color.White
            )
        ) {
            Text("添加")
        }
    }, dismissButton = {
        TextButton(
            onClick = onDismiss, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colors.primary)
        ) {
            Text("取消")
        }
    }, backgroundColor = WeddingThemeColors.BackgroundWhite, shape = RoundedCornerShape(16.dp))
}

@Composable
fun AddUserGroupDialog(checkList: WeddingCheckList, onDismiss: () -> Unit) {
    var userGroup by remember { mutableStateOf("") }

    AlertDialog(onDismissRequest = onDismiss, title = {
        Text("添加使用方", color = MaterialTheme.colors.primary, fontWeight = FontWeight.Bold)
    }, text = {
        Column(modifier = Modifier.padding(top = 8.dp)) {
            Text("使用方名称", fontWeight = FontWeight.Bold, color = MaterialTheme.colors.secondary)
            OutlinedTextField(
                value = userGroup,
                onValueChange = { userGroup = it },
                label = { Text("使用方名称") },
                colors = TextFieldDefaults.outlinedTextFieldColors(
                    focusedBorderColor = MaterialTheme.colors.primary,
                    unfocusedBorderColor = MaterialTheme.colors.primary.copy(alpha = 0.5f),
                    cursorColor = MaterialTheme.colors.primary
                ),
                modifier = Modifier.fillMaxWidth()
            )
        }
    }, confirmButton = {
        Button(
            onClick = {
                if (userGroup.isNotBlank()) {
                    // 添加新的使用方
                    val dummyItem = CheckListItem(
                        id = -1,
                        name = "占位物品", // 创建一个占位物品，确保使用方被添加
                        userGroup = userGroup,
                        purpose = "",
                        location = "",
                        confirmed = false,
                        userDefined = true,
                        isDeleted = false
                    )
                    checkList.addItem(dummyItem)
                    checkList.removeItem(dummyItem) // 立即删除占位物品
                    onDismiss()
                }
            }, enabled = userGroup.isNotBlank(), colors = ButtonDefaults.buttonColors(
                backgroundColor = MaterialTheme.colors.primary, contentColor = Color.White
            )
        ) {
            Text("添加")
        }
    }, dismissButton = {
        TextButton(
            onClick = onDismiss, colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colors.primary)
        ) {
            Text("取消")
        }
    }, backgroundColor = WeddingThemeColors.BackgroundWhite, shape = RoundedCornerShape(16.dp))
}
